//
//  WBComposeTextView.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/13.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

class WBComposeTextView: UITextView {

    fileprivate lazy var placeHolderLabel: UILabel = {
       
        let label = UILabel()
        label.text = "请输入微博内容~"
        label.textColor = UIColor.lightGray
        label.font = UIFont.systemFont(ofSize: 13)
        
        label.numberOfLines = 0
        
        return label
    }()
    
    var placHolder: String? {
        
        didSet {
            placeHolderLabel.text = placHolder
        }
    }
    
    override var font: UIFont? {
        
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 监听 textview 改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        backgroundColor = UIColor.white
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
    }
    
    @objc private func textChange() {
        
        placeHolderLabel.isHidden = hasText
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
